package com.example.bilibili_fake.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.bannerapi.model.BannerItem
import com.example.bilibili_fake.databinding.FragmentRecommendBinding
import com.example.bilibili_fake.utils.LogUtil
import com.youth.banner.Banner
import com.youth.banner.indicator.CircleIndicator

class RecommendFragment : Fragment() {

    private var _binding: FragmentRecommendBinding? = null
    private val binding get() = _binding!!

    private lateinit var homeViewModel: HomeViewModel
    private lateinit var videoAdapter: VideoAdapter
    private lateinit var videoRecyclerView: RecyclerView
    private lateinit var progressBar: ProgressBar
    private lateinit var errorText: TextView
    private lateinit var refreshLayout: com.scwang.smart.refresh.layout.SmartRefreshLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecommendBinding.inflate(inflater, container, false)
        val root: View = binding.root

        homeViewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]

        videoRecyclerView = binding.videoRecyclerView
        progressBar = binding.progressBar
        errorText = binding.errorText
        refreshLayout = binding.refreshLayout

        videoRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)

        setupRecyclerView()
        observeViewModel()
        homeViewModel.loadVideos()
        initBanner()
        refreshAndLoadMore()

        return root
    }

    private fun setupRecyclerView() {
        videoAdapter = VideoAdapter(emptyList())
        videoRecyclerView.adapter = videoAdapter
    }

    private fun observeViewModel() {
        homeViewModel.videos.observe(viewLifecycleOwner) { videos ->
            videoAdapter = VideoAdapter(videos)
            videoRecyclerView.adapter = videoAdapter
        }

        homeViewModel.loading.observe(viewLifecycleOwner) { isLoading ->
            progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        }

        homeViewModel.error.observe(viewLifecycleOwner) { error ->
            if (error != null) {
                errorText.text = error
                errorText.visibility = View.VISIBLE
                Toast.makeText(context, error, Toast.LENGTH_LONG).show()
                LogUtil.e("RecommendFragment", error)
            } else {
                errorText.visibility = View.GONE
            }
        }

        homeViewModel.refreshing.observe(viewLifecycleOwner) { isRefreshing ->
            if (!isRefreshing){
                refreshLayout.finishRefresh(1500)
            }
            LogUtil.d("RecommendFragment", "isRefreshing: $isRefreshing")
        }
        
        homeViewModel.loading.observe(viewLifecycleOwner) { isLoading ->
            if (!isLoading) {
                // 加载完成时结束加载更多状态
                refreshLayout.finishLoadMore()
            }
            progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        }
    }
    
    fun refreshAndLoadMore() {
        refreshLayout.setOnRefreshListener {
            homeViewModel.refreshVideos()
        }
        refreshLayout.setOnLoadMoreListener {
            homeViewModel.loadMoreVideos()
        }
    }
    
    private fun initBanner() {
        val banner = binding.banner

        banner.setIndicator(CircleIndicator(requireContext()))

        homeViewModel.banners.observe(viewLifecycleOwner) { bannerItems ->
            try {
                if (bannerItems != null && bannerItems.isNotEmpty()) {
                    banner.setAdapter(BannerAdapter(bannerItems), true)
                    banner.isInfiniteLoop
                    banner.isAutoLoop(true)
                    banner.visibility = View.VISIBLE
                } else {
                    banner.visibility = View.GONE
                }
            } catch (e: Exception) {
                LogUtil.e("RecommendFragment", "Banner处理异常: ${e.message}")
                banner.visibility = View.GONE
            }
        }
        homeViewModel.loadBanners()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        fun newInstance() = RecommendFragment()
    }
}